/**
Company: Sarkar software technologys
WebSite: http://www.sarkar.cn
Author: yeganaaa
Date : 5/19/18
Time: 4:08 PM
 */

package Cn.Sarkar.Entities.Common

import com.mchange.v2.c3p0.ComboPooledDataSource

class ConnectionPool(val config: Configuration) {
    data class Configuration(
            var database: String = "mysql",
            var driverClass: String = "",
            var userName: String = "root",
            var password: String = "",
            var maxPoolSize: Int = 15,
            var minPoolSize: Int = 5,
            var jdbcUrl: String = "",
            var initialPoolSize: Int = 10,
            var requiredPassword: Boolean = true,
            var retryAttemps: Int = 10
    )

    private val pool by lazy {
        ComboPooledDataSource().also {
            it.driverClass = config.driverClass
            it.user = config.userName
            it.password = config.password
            it.maxPoolSize = config.maxPoolSize
            it.minPoolSize = config.minPoolSize
            it.jdbcUrl = config.jdbcUrl
            it.initialPoolSize = config.initialPoolSize
            it.isAutoCommitOnClose = true
            it.acquireRetryAttempts = config.retryAttemps
        }
    }

    fun getConnection() = pool.connection
    fun close(){
        pool.close()
    }
}